# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import cv2 as cv
import numpy as np
import point


def resize_img(image, height=1800):
    h, w = image.shape[:2]
    pro = height / h
    size = (int(w * pro), int(height))
    img = cv.resize(image, size)
    return img


# path = '/Users/wanggh/Desktop/a.jpeg'
path = '/Users/wanggh/Desktop/abc.jpeg'
# path = '/Users/wanggh/Desktop/b.jpeg'

src = cv.imread(path)
src = resize_img(src)
# 灰度
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# 高斯平滑
gray = cv.GaussianBlur(gray, (3, 3), sigmaX=5, sigmaY=5, borderType=cv.BORDER_DEFAULT)
# 边缘检测
gray = cv.Canny(gray, 25, 50, apertureSize=3, L2gradient=False)
# 膨胀操作，尽量使边缘闭合
kernel = np.ones((3, 3), np.uint8)
gray = cv.dilate(gray, kernel, iterations=0)
ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
max_contour = []
approx_arr = []
max_x = 0
min_x = 0
max_y = 0
min_y = 0
for contour in contours:
    hull = cv.convexHull(contour)
    epsilon = 0.02 * cv.arcLength(contour, True)
    approx = cv.approxPolyDP(hull, epsilon, True)
    if len(approx) == 4:
        # approx
        currentArea = cv.contourArea(approx)
        print(currentArea)
        if 5000 < currentArea:
            x, y, w, h = cv.boundingRect(approx)
            cv.rectangle(src, (x, y), (x + w, y + h), (0, 255, 0), 2)
        if 2400 < currentArea < 4000:
            x, y, w, h = cv.boundingRect(approx)
            if (x + w) > max_x:
                max_x = (x + w)
            if y + h > max_y:
                max_y = (y + h)
            if min_x == 0:
                min_x = x
            elif x < min_x:
                min_x = x
            if min_y == 0:
                min_y = y
            elif y < min_y:
                min_y = y
            approx_arr.append(approx)
            max_contour.append(contour)
# x, y, w, h = cv.boundingRect(contour)
# cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

# 确定四个角
approx_list = []
print(max_x, max_y, min_x, min_y)

lt = point.Point(min_x, min_y)
rb = point.Point(max_x, max_y)
cv.rectangle(src, (lt.x - 5, lt.y - 5), (rb.x + 5, rb.y + 5), (0, 255, 0), 2)
# cv.rectangle(src, (lt.x, lt.y), (-100, -100), (0, 0, 255), 2)

cv.imshow("test", src)
cv.waitKey(0)
cv.destroyAllWindows()
